require 'rubygems'
require 'bundler/setup'
Bundler.require :default
require 'em-synchrony/activerecord'
require 'async_rack'
require_relative './lib/async_csrf'
# require 'goliath/plugins/latency'

APP_ENV = ENV['GOLIATH_BOILERPLATE_APP_ENV'] || 'development'
database_config_file = File.expand_path('../db/config.yml', __FILE__)
database_config = YAML.load(File.read(database_config_file))[APP_ENV]
Dir[File.expand_path("../config/#{APP_ENV}/*.rb", __FILE__)].each { |f| require f }
Dir[File.expand_path('../app/models/*.rb', __FILE__)].each { |f| require f }

require_relative './app/api/v1/api'

# fiber_pool = FiberPool.new(20)

# Goliath::Request.execute_block = proc do |&block|
#   fiber_pool.spawn(&block)
# end

Kaminari::Hooks.init

ActiveRecord::Base.establish_connection(database_config)

class Application < Goliath::API
  use Goliath::Rack::Validation::RequestMethod, %w(GET POST PATCH DELETE OPTIONS)
  use SESSION_STORE, SESSION_OPTIONS
  use AsyncRack::Csrf, header: 'X-Csrf-Token'
  use Goliath::Rack::Params
  # plugin Goliath::Plugin::Latency       # output reactor latency every second

  def response(env)
    status, headers, body = V1::Api.call(env)
    headers.reverse_merge!('X-Csrf-Token' => Rack::Csrf.token(env))
    [status, headers, body]
  end
end